//
//  VOLSoonPublishViewController.m
//  Volver
//
//  Created by administrator on 14-9-16.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLSoonPublishViewController.h"
#import "common.h"
#import "HTTPDefine.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLHouseAllInfoViewController.h"
#import "VOLAppDelegate.h"
#import "VOLEditHouseInfoCell.h"
#import "VOLTITLEViewController.h"
#import "VOLPriceViewController.h"
#import "VOLSummaryViewController.h"
#import "VOLSelectInfViewController.h"
#import "VOLhouseExpirationdateViewController.h"
#import "VOLMyHouseViewController.h"

#import "BWJBaseInfo.h"

//#import "VOLAddHouseImageViewController.h"



@interface VOLSoonPublishViewController ()
{
    NSMutableArray *array ;
    VOLAppDelegate *del ;
    JSONDecoder *jd;
    
    MBProgressHUD *HUD;
    
}
@end

@implementation VOLSoonPublishViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = @"即将发布";
    
    addBackButton();
    
    self.navigationItem.rightBarButtonItem.tintColor = kThemeColor;
    self.publisButton.backgroundColor = kThemeColor;
    //    初始化数组
    array = [NSMutableArray array];
    [array addObject:@"标题"];
    [array addObject:@"撰写摘要"];
    [array addObject:@"价格"];
    [array addObject:@"编辑可选信息"];
    [array addObject:@"编辑截止日期"];
    self.otherInfoTableVIew.dataSource = self ;
    self.otherInfoTableVIew.delegate = self ;
    //初始化一些对象
    del = kGetDel ;
    jd = [[JSONDecoder alloc] init];
    
    //初始化图片数组
    del.selectedHouseImages = [NSMutableArray array];
    //初始化便利设施计数
    del.facilityCount = 0;
    
    //设置tableView不可拖动
    self.otherInfoTableVIew.bounces = NO;
    
    //设置单击手势
    self.addImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self.addImageView addGestureRecognizer:tapGesture];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 刷新数据
-(void)viewWillAppear:(BOOL)animated{
//    NSLog(@"viewwillappear");
    if (del.selectedHouseImages.count) {
        UIImage *image = [UIImage imageWithData:del.selectedHouseImages[0]];
        self.addImageView.image = image;
    }
    else{
        self.addImageView.image = [UIImage imageNamed:@"addPhotosBG.png"];
    }
    [self.otherInfoTableVIew reloadData];
}

#pragma mark 跳转传递参数
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if (![segue.identifier isEqualToString:@"previewImagesSegue"]) {
        VOLHouseAllInfoViewController *houseAllInfo = [segue destinationViewController];

        houseAllInfo.sourceFrom = 0;
    }
    
}

#pragma mark - 按钮点击事件

#pragma mark 返回按钮事件
-(void)goBack:(id)sender{
    back;
}

#pragma mark 点击手势事件
-(void)handleTap:(UITapGestureRecognizer *)recognizer{
    
    NSLog(@"tap");
    if (del.selectedHouseImages.count != 0) {
        [self performSegueWithIdentifier:@"previewImagesSegue" sender:nil];
    }
    else{
        //添加照相动作
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择照片", nil];
        [sheet showInView:self.view];
    }
    
    
}

#pragma mark 发布按钮事件
- (IBAction)publish:(id)sender {

    //检测不能为空的项目
    NSMutableString *alertStr = [NSMutableString string];
    //图片
    if (del.selectedHouseImages.count == 0) {
        if ([alertStr isEqualToString:@""]) {
            [alertStr appendString:@"图片"];
        }else{
            [alertStr appendString:@"、图片"];
        }
        
    }
    //标题
    if (del.publishHouse.houseTitle == nil) {
        if ([alertStr isEqualToString:@""]) {
            [alertStr appendString:@"标题"];
        }else{
            [alertStr appendString:@"、标题"];
        }
        
    }
    //摘要
    if (del.publishHouse.houseDesc == nil) {
        if ([alertStr isEqualToString:@""]) {
            [alertStr appendString:@"摘要"];
        }else{
            [alertStr appendString:@"、摘要"];
        }
    }
    //价格
    if (del.publishHouse.housePrice == 0) {
        if ([alertStr isEqualToString:@""]) {
            [alertStr appendString:@"价格"];
        }else{
            [alertStr appendString:@"、价格"];
        }
        
    }
    //可选信息部分不做判断
    //截止日期
    if (del.publishHouse.houseExpirationdate == 0) {
        if ([alertStr isEqualToString:@""]) {
            [alertStr appendString:@"截止日期"];
        }else{
            [alertStr appendString:@"、截止日期"];
        }
        
    }
    
    //如果alertStr不为nil，就要显示alert提醒
    if (![alertStr isEqualToString:@""]) {
        [alertStr appendString:@"不能为空！"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:alertStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    
    __block BOOL isSubmit = NO;
    
    //初始化提示框
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    HUD.labelText = @"正在上传...";
    
    [HUD showAnimated:YES whileExecutingBlock:^{
#pragma mark 调用添加方法，将房屋添加到数据库
        //上传房屋便利设施，成功后得到便利设施ID
        int tempFacilityID = [self submitFacility:del.publishFacility];
        if (tempFacilityID) {
            //如果便利设施上传成功，再上传房屋信息
            int tempHouseID = [self submitHouse:del.publishHouse facilityID:tempFacilityID];
            if (tempHouseID >= 0) {
                
                //如果房屋上传成功，再上传图片，返回上传成功图片的数量
                int finishedImageNum = [self submitHouseImages:del.selectedHouseImages houseID:tempHouseID];
                
                if (finishedImageNum == del.selectedHouseImages.count) {//全部上传成功
                    
                    //更改isSubmit
                    isSubmit = YES;
                    
                }
                else{
                    int failNum = del.selectedHouseImages.count - finishedImageNum;
                    NSLog(@"%d张图片上传失败！",failNum);
                }
                
            }
            else{
                NSLog(@"房屋添加失败");
                return;
            }
        }
        else{
            NSLog(@"便利设施添加失败，程序结束");
            return;
        }
    } completionBlock:^{
        
        //移除正在加载提示
        [HUD removeFromSuperview];
        HUD = nil;
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        if (isSubmit) {
            HUD.labelText = @"发布成功";
            HUD.mode = MBProgressHUDModeCustomView;
            HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
        }
        else{
            HUD.labelText = @"操作成功";
            HUD.mode = MBProgressHUDModeText;
        }
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            //发布成功后清除publishHouse
            del.publishHouse = nil;
            del.publishFacility = nil;
            NSLog(@"消除成功");
            del.isRefresh = 3;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }];
    

    
}

#pragma mark - 将房屋、便利设施、图片上传到数据库
#pragma mark 上传便利设施
-(int)submitFacility:(Facility *)facility{
    
    //URL
    NSString *urlstr = [NSString stringWithFormat:@"%@facility/addFacility?shampoo=%d&aircondition=%d&kitchen=%d&wifi=%d&hotwater=%d&parking=%d&elevator=%d&isSmoke=%d&isPat=%d&barrierFree=%d&tv=%d&bathroom=%d",kHTTPHome,facility.shampoo,facility.aircondition,facility.kitchen,facility.wifi,facility.hotwater,facility.parking,facility.elevator,facility.isSmoke,facility.isPat,facility.barrierFree,facility.tv,facility.bathroom];
    NSURL *url = [NSURL URLWithString:urlstr];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    //接收返回数据
    NSData *data = [request responseData];
    NSDictionary *dic = [jd objectWithData:data];
    
    int result = [[dic objectForKey:@"result"] intValue];
    if (result) {
        //添加成功时返回一个便利设施记录的ID
        NSLog(@"便利设施添加成功");
        return [[dic objectForKey:@"f_id"] intValue];
    }else{
        //添加失败时返回-1
        return -1;
    }
    
}

#pragma mark 上传房屋信息
-(int)submitHouse:(House *)house facilityID:(int)facilityID{
    
    //得到即将发布房屋的便利设施ID
    house.houseFacility = facilityID;
    //设置房子状态为可出租
    house.houseStatus = 1;
    //设置房屋的拥有者为当前登录的用户
    house.houseOwner = del.currentUser.userID;
    
    NSString *urlstr = [NSString stringWithFormat:@"%@house/addHouse",kHTTPHome];
    
    NSURL *url = [NSURL URLWithString:urlstr];
    
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    
    
    //添加POST请求数据
    
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseType] forKey:@"houseType"];
    [request setPostValue:house.houseProvince forKey:@"houseProvince"];
    [request setPostValue:house.houseCity forKey:@"houseCity"];
    [request setPostValue:house.houseStreet forKey:@"houseStreet"];
    
    [request setPostValue:[NSString stringWithFormat:@"%f",house.houseLongitude] forKey:@"houseLongitude"];
    [request setPostValue:[NSString stringWithFormat:@"%f",house.houseLatitude] forKey:@"houseLatitude"];
    
    [request setPostValue:[NSString stringWithFormat:@"%d",house.housePersons] forKey:@"housePersons"];//人数
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseBedroom] forKey:@"houseBedroom"];//房间数
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseBed] forKey:@"houseBed"];//床位数
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseToilet] forKey:@"houseToilet"];//卫生间数
    
    [request setPostValue:house.houseTitle forKey:@"houseTitle"];//标题
    [request setPostValue:house.houseDesc forKey:@"houseDesc"];//描述
    
    [request setPostValue:[NSString stringWithFormat:@"%f",house.housePrice] forKey:@"housePrice"];//价格
    
    [request setPostValue:house.houseNear forKey:@"houseNear"];//附近
    [request setPostValue:house.houseTraffic forKey:@"houseTraffic"];//交通
    [request setPostValue:house.houseNotice forKey:@"houseNotice"];//注意事项
    
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseStatus] forKey:@"houseStatus"];//状态
    
    [request setPostValue:[NSString stringWithFormat:@"%f",house.houseDate] forKey:@"houseDate"];//发布日期
    [request setPostValue:[NSString stringWithFormat:@"%f",house.houseExpirationdate] forKey:@"houseExpirationdate"];//失效日期
    
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseFacility] forKey:@"houseFacility"];//便利设施ID
    [request setPostValue:[NSString stringWithFormat:@"%d",house.houseOwner] forKey:@"houseOwner"];//房东ID
    
    
    [request setRequestMethod:@"POST"];
    
    [request startSynchronous];
    
    //接收返回数据
    NSData *data = [request responseData];
    if (data != nil) {
        NSLog(@"%@",data);
        NSDictionary *dic = [jd objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status) {
            int newHouseID = [[dic objectForKey:@"house"] intValue];
            return newHouseID;
        }else{
            NSLog(@"房屋添加失败");
            return -1;
        }
    }
    else{
        NSLog(@"data为空");
        return -2;
    }
}

#pragma mark 上传房屋图片
-(int)submitHouseImages:(NSArray *)imagesArray houseID:(int)houseID{
    
    int finishedImageCount = 0;
    
    //循环上传图片，每次上传一张
    for (NSMutableData *imageData in imagesArray) {
        NSString *urlstr = [NSString stringWithFormat:@"%@upload/upload",kHTTPHome];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlstr]];
        
        [request setValidatesSecureCertificate:NO];
        request.shouldAttemptPersistentConnection = NO;
        [request addRequestHeader:@"Content-Type" value:@"binary/octet-stream"];
        
        
        //        [request setDelegate:self];
        [request setRequestMethod:@"POST"];
        
        //传递houseID和图片类型信息
        [request setPostValue:@"houseImages" forKey:@"subfileName"];
        [request setPostValue:[NSString stringWithFormat:@"%d",houseID] forKey:@"subID"];
        
        [request addData:imageData withFileName:@"header.png" andContentType:@"image/png" forKey:@"file"];
        [request startSynchronous];
        
        NSData *data = [request responseData];
        NSDictionary *dic = [jd objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status >= 0) {
            finishedImageCount++;
        }
    }
    return finishedImageCount;
    
}

#pragma mark - alert代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [array count];
}

#pragma mark-通过判断属性有无值来改变cell的外观
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VOLEditHouseInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kcell" forIndexPath:indexPath ];
    
    if (indexPath.row == 0) {//有值
        if (del.publishHouse.houseTitle && ![del.publishHouse.houseTitle isEqualToString:@""]) {
            
            cell.textsLabel.text = [NSString  stringWithFormat:@"标题：%@", del.publishHouse.houseTitle] ;
            //字体变红
            cell.textsLabel.textColor = [UIColor redColor];
            //选中状态
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {//无值
            cell.textsLabel.text = [array objectAtIndex:[indexPath row]];
            cell.textsLabel.textColor = [UIColor blackColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else if (indexPath.row == 1) {
        if (del.publishHouse.houseDesc && ![del.publishHouse.houseDesc isEqualToString:@""]) {
            cell.textsLabel.text = [ NSString stringWithFormat:@"摘要:%@", del.publishHouse.houseDesc]  ;
            NSLog(@"%@",cell.textLabel.text);
            cell.textsLabel.textColor = [UIColor redColor];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            cell.textsLabel.text = [array objectAtIndex:[indexPath row]];
            cell.textsLabel.textColor = [UIColor blackColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    
    else if (indexPath.row == 2) {
        if (del.publishHouse.housePrice != 0) {
            cell.textsLabel.text = [NSString stringWithFormat:@"价格：%.1f元/天",del.publishHouse.housePrice];
            cell.textsLabel.textColor = [UIColor redColor];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            cell.textsLabel.text = [array objectAtIndex:[indexPath row]];
            cell.textsLabel.textColor = [UIColor blackColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else if(indexPath.row == 3 ){
        
        if ((del.publishHouse.houseTraffic == nil && del.publishHouse.houseNear == nil && del.facilityCount == 0)
            || ([del.publishHouse.houseTraffic isEqualToString:@""] && [del.publishHouse.houseNear isEqualToString:@""] && del.facilityCount == 0)) {
            cell.textsLabel.text = [array objectAtIndex:[indexPath row]];
            cell.textsLabel.textColor = [UIColor blackColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }else{
            cell.textsLabel.text = @"可选信息(已选)";
            cell.textsLabel.textColor = [UIColor redColor];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else if(indexPath.row == 4 ){
        
        if (del.publishHouse.houseExpirationdate != 0) {

            NSDate *date =  kTransformToDate(del.publishHouse.houseExpirationdate);
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"截止日期:yyyy年MM月dd日"];
            cell.textsLabel.text = [formatter stringFromDate:date];
            cell.textsLabel.textColor = [UIColor redColor];
            
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            cell.textsLabel.text = [array objectAtIndex:[indexPath row]];
            cell.textsLabel.textColor = [UIColor blackColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    return cell ;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        VOLTITLEViewController *title = [[VOLTITLEViewController alloc]init];
        [self.navigationController pushViewController:title animated:YES];
    }
    else if (indexPath.row == 1){
        VOLSummaryViewController *zhaiyao = [[VOLSummaryViewController alloc]init];
        [self.navigationController pushViewController:zhaiyao animated:YES];
    }
    else if (indexPath.row == 2){
        VOLPriceViewController *price = [[VOLPriceViewController alloc] init];
        [self.navigationController pushViewController:price animated:YES];
    }
    else if (indexPath.row == 3){
        
        VOLSelectInfViewController *sel = [[VOLSelectInfViewController alloc]initWithNibName:@"VOLSelectInfViewController" bundle:nil];
        [self.navigationController pushViewController:sel animated:YES];
    }
    else if (indexPath.row == 4){
        
        VOLhouseExpirationdateViewController *exp = [[VOLhouseExpirationdateViewController alloc] initWithNibName:@"VOLhouseExpirationdateViewController" bundle:nil];
        [self.navigationController pushViewController:exp animated:YES];
    }
}


#pragma mark - 添加图片功能所有函数
#pragma mark - actionsheet代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"照相");
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            //设置代理
            imagePicker.delegate = self;
            
            //判断是否有后置摄像头
            if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
                NSLog(@"没有摄像头");
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//照相机
            
            //调用摄像头开始拍照
            [self presentViewController:imagePicker animated:YES completion:^{
                
            }];
            break;
        }
            
            
            
        case 1:
        {
            NSLog(@"选照片");
            //第一次使用时初始化这个数组
            if (!del.selectedHouseImages)
                del.selectedHouseImages = [[NSMutableArray alloc] init];
            
            //创建照片选取器
            ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
            picker.maximumNumberOfSelection = 10;
            picker.assetsFilter = [ALAssetsFilter allPhotos];
            picker.showEmptyGroups=NO;
            picker.delegate=self;
            picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
                if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                    return duration >= 5;
                } else {
                    return YES;
                }
            }];
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
            
            break;
            
        case 2:
            NSLog(@"cancel");
            return;
            break;
            
            
    }
}



#pragma mark - UIImagePickerController代理方法，拍照结束后全调用这个方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取拍到的照片
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //将image转化成NSData,并加入到数组
    NSData *data = UIImageJPEGRepresentation(image, kCompressionRatio);
    [del.selectedHouseImages addObject:data];
    //图片加入数组后，将拍照这个界面关闭
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    
    //取出图片,并添加到数组
    NSMutableArray *willAddImages = [NSMutableArray array];
    
    for (int i = 0; i < assets.count; i++) {
        ALAsset *asset = assets[i];
        //获取图片，并将图片压缩后，转化成NSData加入到数组中
        UIImage *image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [willAddImages addObject:UIImageJPEGRepresentation(image, kCompressionRatio)];
        
    }
    
    
    
    //查检图片是否有重复的
    NSArray *resultArray = [NSArray array];
    
    if (del.selectedHouseImages.count) {
        resultArray = [self checkImageRepeat:willAddImages];
    }else{
        resultArray = willAddImages;
    }
    
    [del.selectedHouseImages addObjectsFromArray:resultArray];
}

#pragma mark 转化indexPath方法
- (NSArray *)indexPathOfNewlyAddedAssets:(NSArray *)transformArray
{
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    
    for (NSInteger i = del.selectedHouseImages.count; i < del.selectedHouseImages.count + transformArray.count ; i++)
        [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    
    return indexPaths;
}

#pragma mark 图片数组查重
-(NSArray *)checkImageRepeat:(NSArray *)assets{
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    
    //循环检查图片是否有重复的
    for (int i = 0; i < assets.count; i++) {
        if (![del.selectedHouseImages containsObject:assets[i]]) {//当图片不在数组中时，添加
            [tempArray addObject:assets[i]];
        }
    }
    return  tempArray;
}


@end







